Skip to content

feat(api): generate the frontend API contract with Kubb - #3

Merged
pdevito3 merged 101 commits into
mainfrom
feat/kubb-contracts
Oct 18, 2026
Merged

pdevito3 merged 101 commits into
mainfrom
feat/kubb-contracts

Conversation

@pdevito3

@pdevito3 pdevito3 commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Generates the frontend API contract with Kubb, with one file for each endpoint.

Merge #5 first. This branch has the commits of #5, and they drop out of this diff after the merge.

Changes

  • Microsoft.AspNetCore.OpenApi writes the OpenAPI document at build time. SwaggerGen is removed. Swagger UI stays, and only Development serves it.
  • Kubb (plugin-ts, axios, zod) writes the types, clients, and schemas to frontend/src/api/generated/. Each OpenAPI document gets its own folder: generated for v1, generated-v2 for v2, and more.
  • The generated clients send each request through apiClient, so they get the CSRF header, the cookies, and the error toasts.
  • The document and the generated files are committed. The api-contract job of the CI workflow deletes them, generates them again, and fails when they are not current. A document of a removed API version also fails the job.
  • The Kubb telemetry is off. The Kubb update check to registry.npmjs.org has no opt-out.
  • The list endpoints sort by Id after each sort, so a row cannot show on two pages. A composite index serves the default sort of the user list.
  • PagedList.CreateAsync counts the rows asynchronously. PagedList uses checked math for the page offset.
  • ApplyFilters and ApplySortOrder wrap QueryKit. They throw a QueryInputException with the name of the parameter that failed.
  • Each domain guard takes the name of the request field, so each 422 has a key in errors.
  • The backend-feature skill has a step that generates the contract.
  • pnpm 10.34.7 is pinned in packageManager. CI and the BFF Dockerfile use this version. Only esbuild can run an install script.

Behavior changes

Update the API clients outside this repo for these changes:

  • Filter and sort on the DTO: filters and sortOrder apply to the DTO fields only. A field that the DTO does not show, for example CreatedBy, gives 400.
  • Bad QueryKit input: a filters or sortOrder value that QueryKit cannot apply gives 400, not 500. The key in errors is the parameter that failed, for example sortOrder for Name foo. An operator that does not fit the property type, for example Name ^^ "x", gives 400 with the fixed message "The filters value is not valid.".
  • API versions: an endpoint answers only on the API versions that it declares. An undeclared version gives 404.
  • Error keys: the keys of the errors field are the request field names in camelCase. For example: email, firstName, role, permission, and tenantId. A blank tenant name on initiate uses tenantName.
  • Query parameters: the names are camelCase: filters, sortOrder, pageNumber, and pageSize.
  • Duplicates: a duplicate unique value gives 409, not 422. A duplicate user gives the key identifier. A duplicate tenant name gives the key name, or tenantName on initiate. Initiate now checks the tenant name before the save.
  • Paging: a pageNumber or a pageSize less than 1 gives 400. A pageNumber more than 4294967 gives 400, not 500.
  • Error content type: each error response has the content type application/problem+json.
  • Packages: Asp.Versioning 8.1 to 10.2, QueryKit 1.12 to 1.16.1, Microsoft.AspNetCore.OpenApi 10.0.1 to 10.0.13, axios 1.13 to 1.20, and pnpm 9 to 10.
  • Workflow: the API contract workflow is now .github/workflows/ci.yml, with the name CI. Update each required status check that uses the old name.

Tests

  • The OpenAPI document tests check each rule of the document. They cover four transformers, and unit tests cover the other three.
  • The unit tests cover each status that DomainProblemDetails maps: 400, 404, 409, 422, and 500. A unit test fails if a unique index in the model has no request field.
  • The functional tests cover the status, the body, and the error keys of the 400, 401, 404, 409, and 422 responses.
  • The functional tests cover the default sort of the user list, the filters on each field of the user DTO (Permissions included), and the X-Pagination header.
  • A functional test reads five users with the same role, one for each page. Each user shows on exactly one page, in Id order. The test fails when the tie-break on Id is deleted. A tenant test cannot fail this way, because the tenant names are unique.
  • Vitest covers parsePagination, problem-details, and the apiClient interceptor through a generated client.

Known limits

Fast refresh only works when a file exports only components. Move the cva variants, hooks, contexts, and the Notification API to their own files next to the components, and update the imports. The public names do not change.
The filter-demo route imported types inline with values. With verbatimModuleSyntax the route split left a side-effect import of the filter builder in the route file, so the filter builder, the calendar, and react-aria went into the entry chunk. Import the types with import type.

Also put the vendor libraries that the root layout always loads (react, the router, the query client, motion) in their own chunks. The entry chunk goes from 897 kB to 288 kB, and the build has no chunk size warning.
The project rules forbid barrel files. The filter-builder barrel also caused the large entry chunk: an import of it from the filter demo route pulled the whole filter builder into the entry. The route now imports from each source file.
The project rules forbid barrel files, and nothing imported this one.
The three theme buttons were wider than the icon rail, so the rail clipped them. The buttons now stack vertically in the rail.
The variants use the destructive color for text, but the dark value was too dark to read on the dark background. The dark value is now the current shadcn value.
No file imports the useComboboxFilter hook. Remove the file.
@pdevito3
pdevito3 force-pushed the feat/kubb-contracts branch from e13e230 to 5ba98f3 Compare October 18, 2026 16:07
Remove the old filter hook comments in the autocomplete and combobox files. Rename notifications.tsx to toaster.tsx, because the file holds the Toaster.
The name Notifications was too close to the Notification API that shows a toast. The JSDoc now says that the component is the container, and that Notification shows a toast.
A Debug build of the Server writes the OpenAPI document to FullstackTemplate.Server/openapi/. Kubb generates one client, type, and Zod file for each endpoint in frontend/src/api/generated/. The weather hooks use the generated clients. A CI workflow fails when the committed contract is not current. See docs/adr/0001-commit-generated-api-contract.md.
GetDocument.Insider starts the host to read the endpoints, so each hosted service ran during a Debug build. With a connection string in the environment, the build applied migrations to that database, or failed with ObjectDisposedException when the database was not available. The build-time run now removes all hosted services.
A global Produces("application/json") filter was added only so that each
operation in the OpenAPI document had one media type. The filter also
changed the responses at run time: a 400 for malformed JSON and a
NotFound() from a controller had the content type application/json
instead of application/problem+json. Only the errors from the exception
handler still sent problem+json, and the document listed each
ProblemDetails response as application/json.

Remove the filter, so MVC sends ProblemDetails as application/problem+json
again. Add JsonContentTypeTransformer, which keeps one media type for each
response in the document: application/problem+json for a response that
returns ProblemDetails, and application/json for the other responses.
Add functional tests for malformed JSON and for NotFound().

The generated Kubb files do not change, because Kubb reads both media
types as JSON.
Strict number handling (for MVC and for minimal APIs) and a JSON input
formatter limited to application/json were added only to change the
OpenAPI document: to type numbers as integer instead of integer or
string, and to remove the text/json and application/*+json request body
types. They also changed the runtime behavior: a text/json body got 415,
and a number sent as a string got 400.

Restore the ASP.NET defaults in AddControllers. Add
RemoveStringFromNumbersTransformer, which removes the string type and
its pattern from number and integer schemas, and make
JsonContentTypeTransformer keep only application/json for request
bodies. The Server accepts the lenient forms again, but the contract
states only the canonical form. The OpenAPI document and the generated
Kubb files do not change. Add a functional test for a text/json body.
A list client returns the full response only because its operationId
ends in "List". Nothing checked that rule, so a renamed list endpoint
got a client that silently dropped the X-Pagination header. Callers
also had to read and JSON.parse the header by hand, and no test checked
the shape of the header.

- Add RequireListOperationNameTransformer. The OpenAPI build now fails
  when an operation documents the X-Pagination header but its name does
  not end in "List", or when its name ends in "List" but it has no such
  header. The message names the endpoint and tells how to fix it.
- Add parsePagination in frontend/src/lib/pagination.ts. It reads the
  header from the full result of a list client and returns the
  generated PaginationMetadata type.
- Add a functional test that calls the user list endpoint and checks
  the property names and value types of the X-Pagination header.
- Document the naming rule and the helper.
The package was on 10.0.1. Version 10.0.13 is the newest patch of the .NET 10 release. Main already updates Microsoft.OpenApi to 2.12.2.
…crosoft.AspNetCore.OpenApi

Both packages come from the same ASP.NET Core release, so they now use the same version, 10.0.13. The OpenAPI document does not change.
Extract the X-Pagination assertion into a helper and use it for the user list and the tenant list. The tenant list is not tenant scoped, so the test filters on a unique name.
A 400 comes from model binding or model validation, and the Server sends a ValidationProblemDetails body with the errors field. The controllers now declare that type, so the OpenAPI document and the generated contract state the real shape. The controller rule and the backend doc say to do the same for new controllers.
Both jobs restore the NuGet package folder with actions/cache. The key uses the OS and the hash of the package and project files. The checkout steps do not keep the token in the git config. The test job does not write the OpenAPI document again, because the api-contract job checks it.
A Debug build of the Server writes the OpenAPI document. GitHub now collapses it in pull request diffs, as it does for the Kubb output.
Only a Debug build writes the document, so only a Debug build fails on a bad endpoint name. The build-time run does no OIDC discovery. Thus the committed file has no OAuth2 security scheme. The runtime document has it.
The frontend had no unit test runner. Add Vitest and a test script. Vitest uses vite.config.ts, so the @/ alias works. The tests cover a valid header, a header in a different case, a missing header, and a header that is not JSON.
…tConfig alias

The alias added no fields after the suppressErrorToast option moved into the axios module augmentation.
With throwOnError false, axios accepts all statuses. The apiClient error interceptor does not run, so there is no toast and no ProblemDetailsError. Describe this mode next to the default mode.
The ui variants are in *-variants.ts files and the hooks are in use-*.ts files. A component from shadcn add imports them from the component file. Tell the reader to change that import.
A header name is case-insensitive. parsePagination did a property lookup, so headers that a test builds with a mixed-case name gave an error. The lookup now ignores the case.
The composite index (tenant_id, last_name, first_name, id) matches the tenant filter and the default sort of GetUserList. It replaces the index on tenant_id alone, because TenantId is the first column.
@pdevito3
pdevito3 force-pushed the feat/kubb-contracts branch from 5ba98f3 to 9489837 Compare October 18, 2026 18:32
A page number less than 1 gave a negative OFFSET, and a negative page size gave a negative LIMIT. PostgreSQL rejected both, so the request got a 500. A page size of 0 gave a 200 with totalPages 2147483647 and hasNext true. The contract now states a minimum of 1 for both values.
AddTenant and UpdateTenant now check for the name before the save and throw a ConflictException on name. Before, the unique index stopped the save, and the 409 had an empty errors object, so a form could not show the error on the name field. The update check does not count the tenant itself.
…ermission errors

AddUser gave the key TenantId, and Permission gave the key Permission. The keys are now tenantId and permission, the same as the role, email, and identifier keys.
Only the BFF has CORS, and the browser calls the BFF on the same origin as the SPA, so the Access-Control-Expose-Headers entry had no effect. The filter tests now check the page data in the header, and that a result that is not a paged list gets no header.
The comment said that a request without a version gets the default version. The version is in the URL path, and the branch removed AssumeDefaultVersionWhenUnspecified, so no request is without a version.
…roup the imports

The JSDoc of apiClient used /api/weather and post(url, { body }), and both were wrong. The example now calls a generated client, and uses apiClient directly only for /bff/user. The imports of api-client.ts and the weather hooks now obey the external, internal, relative grouping.
…ted again

The build and the generate step do not delete the document or the generated folder of a removed API version. CI now deletes the committed files first, so a stale file shows in the diff as a deleted file. docs/backend.md now gives the steps to remove a version.
The docs named only src/api/generated/. Each API version after v1 has its own folder, for example src/api/generated-v2/, and the rule to not edit applies to each folder.
…ns of a user works

On 1.16.0, `Permissions ^$ "x"` returned 400 and `Permissions == "x"` returned 500, because QueryKit did not treat an IReadOnlyList<string> as a collection (pdevito3/QueryKit#201).
Resolve the conflicts with the change to prefixed string IDs:

- Keep the typed 400 and 422 responses with the string id parameters.
- Keep the route names of main, and add GetByIdentifier.
- Expect the key tenantId in the tenant ID test of main.
- Set the IDs of the default sort test through the creation model.
- Move the filter conversion case to the permission count of the
  user list, because the tenant DTO has only string fields now.
- Generate the contract again. The IDs are strings, not uuids.
A bad sort direction threw QueryKitParsingException, so its error had the key filters. An operator that does not fit the property type, for example ^^ on a string, threw an ArgumentException and gave 500.

ApplyFilters and ApplySortOrder now wrap the QueryKit calls. They throw a QueryInputException with the name of the parameter. A listed QueryKit input error keeps its message. A .NET exception gets a fixed message, because its message names .NET types, and the trace gets the exception.
A domain guard took no field, so the problem had an empty errors object.
Each guard now takes the name of the request field.

InitiateUserAndTenant checks for a taken tenant name and returns a 409
with the key tenantName. A blank tenant name has the key tenantName too.

The 409 for a unique index now names the field of the index. A unit test
makes sure that each unique index in the model has a field.
A large pageNumber wrapped the offset to a negative value, and the list
returned 500. pageNumber now has a maximum of int.MaxValue / 500, so the
list returns 400 with the key pageNumber. PagedList uses checked math as
a second guard.
Five users with the same role, read one for each page, each show on
exactly one page, in Id order. The test fails when the tie-break on Id
is deleted. A tenant test cannot fail, because the tenant names are
unique.
CI used pnpm 9, which runs the install script of each package. pnpm 10
runs only the scripts of onlyBuiltDependencies. CI and the BFF Dockerfile
now take the pnpm version from packageManager in frontend/package.json.
# Conflicts:
#	frontend/src/lib/api-client.ts
#	frontend/src/main.tsx
@pdevito3
pdevito3 marked this pull request as ready for review October 18, 2026 21:25
@pdevito3
pdevito3 merged commit 776510a into main Oct 18, 2026
2 checks passed
@pdevito3
pdevito3 deleted the feat/kubb-contracts branch October 18, 2026 21:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant